package com.fesine.crm.service.impl;

import com.fesine.commons.excel.ObjectExcelRead;
import com.fesine.commons.excel.PageData;
import com.fesine.commons.util.DateUtils;
import com.fesine.crm.exception.CrmException;
import com.fesine.crm.po.AttendanceInfoPo;
import com.fesine.crm.po.EmployeeInfoPo;
import com.fesine.crm.po.FileInfoPo;
import com.fesine.crm.po.NameComparePo;
import com.fesine.crm.service.AttendanceInfoService;
import com.fesine.crm.service.CrmFileService;
import com.fesine.dao.model.QueryResult;
import com.fesine.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2017/10/11 19:55
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/10/11 19:55
 */
@Service("attendanceInfoService")
public class AttendanceInfoServiceImpl extends BaseServiceImpl<AttendanceInfoPo> implements AttendanceInfoService,CrmFileService {
    private static final Logger logger = LoggerFactory.getLogger(AttendanceInfoServiceImpl.class);


    @Override
    public QueryResult<AttendanceInfoPo> listPage(AttendanceInfoPo po, int page, int limit) {
        //处理用户名问题
        if (po.getName() != null) {
            NameComparePo empPo = new NameComparePo();
            empPo.setEmpName(po.getName());
            empPo = daoService.selectOne(empPo);
            if (null != empPo) {
                po.setName(empPo.getAttName());
            }
        }
        return daoService.selectQueryResult(po, page, limit);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importFile(File file) throws Exception {
        Map<String, Boolean> map = new HashMap<>();
        //从第1行开始读取数据
        List<Object> ol = ObjectExcelRead.readExcel(file.getName(), file, 0, 0, 0);
        //处理数据之前，需要登记文件表 exeStatus默认0
        FileInfoPo fileInfoPo = new FileInfoPo();
        fileInfoPo.setFileName(file.getName());
        //2017-09-30 17:39:31 --->2017-09
        String monthStr = (String) ((PageData) ol.get(1)).get("var3");
        fileInfoPo.setMonthStr(monthStr.substring(0, 7));
        daoService.insert(fileInfoPo);
        //验证文件头
        PageData head = (PageData) ol.get(0);
        if(!"持卡人".equals(head.get("var2"))){
            throw new CrmException(500,"请确认第3列为持卡人字段");
        }
        if(!"事件时间".equals(head.get("var3"))){
            throw new CrmException(500,"请确认第4列为事件时间字段");
        }
        if(!"卡号".equals(head.get("var4"))){
            throw new CrmException(500,"请确认第5列为卡号字段");
        }
        if(!"事件源".equals(head.get("var5"))){
            throw new CrmException(500,"请确认第6列为事件源字段");
        }
        if(!"事件类型".equals(head.get("var6"))){
            throw new CrmException(500,"请确认第7列为事件类型字段");
        }
        if(!"控制器名称".equals(head.get("var7"))){
            throw new CrmException(500,"请确认第8列为控制器名称字段");
        }
        AttendanceInfoPo attendanceInfoPo;
        NameComparePo ncPo;
        EmployeeInfoPo empPo;
        String nameTemp = null;
        int count=0;
        Long startTime = System.currentTimeMillis();
        for (int i=1;i<ol.size();i++) {
            PageData pg = (PageData) ol.get(i);
            String name = (String) pg.get("var2");
            if (StringUtils.isBlank(name)) {
                continue;
            }
            //为空，第一次添加，进入验证
            if(map.get(name) ==null){
                count++;
                logger.info("数据库验证 {}", name);
                nameTemp = name;
                ncPo = new NameComparePo();
                ncPo.setAttName(name);
                ncPo = daoService.selectOne(ncPo);
                //此操作用于获取打卡姓名和本人姓名不相同真实姓名
                if (ncPo != null) {
                    name = ncPo.getEmpName();
                    logger.info("行方卡姓名 {} ,本人姓名 {}", name, nameTemp);
                }
                empPo = new EmployeeInfoPo();
                empPo.setName(name);
                empPo = daoService.selectOne(empPo);
                //此判断过滤不是本公司员工数据
                if (empPo == null) {
                    logger.info("不是本公司员工 {}", name);
                    map.put(name, false);
                    continue;
                } else {
                    map.put(name, true);
                }
            }
            if (map.get(name)) {
                logger.info("----->登记数据库 {}", nameTemp);
                attendanceInfoPo = new AttendanceInfoPo();
                attendanceInfoPo.setCompany((String) pg.get("var0"));
                attendanceInfoPo.setJobNo((String) pg.get("var1"));
                attendanceInfoPo.setName((String) pg.get("var2"));
                attendanceInfoPo.setEventTime(DateUtils.formatString((String) pg.get("var3")));
                attendanceInfoPo.setCardNo((String) pg.get("var4"));
                attendanceInfoPo.setEventSource((String) pg.get("var5"));
                attendanceInfoPo.setEventType((String) pg.get("var6"));
                attendanceInfoPo.setControllerName((String) pg.get("var7"));
                attendanceInfoPo.setCreateTime(new Date());
                //0新导入，1已分析
                attendanceInfoPo.setRemark2("0");
                daoService.insert(attendanceInfoPo);
            }
        }
        Long endTime = System.currentTimeMillis();
        logger.info("-----> {}导入成功!共耗时 {} 秒!验证数据 {} 次!", file.getName(),(endTime-startTime)/1000,count);
    }

    @Override
    public int update(AttendanceInfoPo setPo, AttendanceInfoPo wherePo) {
        return daoService.update(setPo,wherePo);
    }
}
